package com.jigu.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.jigu.admin.mapper.console.MenuMapper;
import com.jigu.admin.model.console.Menu;
import com.jigu.admin.service.MenuService;
import com.jigu.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by toretto on 2017/6/22.
 */
@Service
public class MenuServiceIml implements MenuService {


    @Autowired private MenuMapper menuMapper;

    @Override
    public List<Menu> getChildMenuList(ArrayList<Menu> menuList, String parentId) {

        Example example = new Example(Menu.class);
        example.createCriteria().andCondition("parent_id = ", parentId);
        PageHelper.orderBy("listorder asc, created_at desc");
        List<Menu> lists = menuMapper.selectByExample(example);

        for (Menu menu: lists) {
            menuList.add(menu);
            getChildMenuList(menuList, menu.getMenuId());
        }
        return menuList;
    }

    @Override
    public List<Menu> getAllMenus() {

        //从缓存或数据库中查询全部
        PageHelper.orderBy("listorder asc, created_at desc");
        List<Menu> menus = menuMapper.selectAll();

        //获取根分类
        List<Menu> roots = menus.stream().filter(menu -> ("0".equals(menu.getParentId()))).collect(Collectors.toList());

        //获取非根分类
        List<Menu> subs = menus.stream().filter(menu -> (!"0".equals(menu.getParentId()))).collect(Collectors.toList());

        //递归构建结构化的分类信息
        roots.forEach(root -> buildSubs(root, subs));

        return roots;
    }


    /**
     * 递归构建
     * @param parentMenu
     * @param subs
     */
    private void buildSubs(Menu parentMenu, List<Menu> subs){

        List<Menu> childrens = subs.stream()
                .filter(menu -> (StringUtils.equals(menu.getParentId(),parentMenu.getMenuId()))).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(childrens)){
            parentMenu.setChildren(childrens);
            //进行递归构建
            childrens.forEach(child -> buildSubs(child, subs));
        }

    }


}
